//
//  ESWeiXinSelectedViewController.m
//  EasyStyle
//
//  Created by FK on 15/12/18.
//  Copyright © 2015年 FK. All rights reserved.
//

#import "ESWeiXinSelectedViewController.h"
#import "ESWeiXinNewsDetailViewController.h"
#import "ESWeChatReadHistoryDAO.h"
#import "ESWeChatLoadingView.h"
#import "ESWeChatTableViewcell.h"
#import "ESNetViewModelBase.h"
#import "ESWeixinNetResult.h"
#import "ESWeChatNetTask.h"
#import "ESWeChatDAO.h"
#import "MJRefresh.h"


static NSString * const kESWeiXinSelectedVCLastedUpdateTimeKey = @"ESWeiXinSelectedVC_MJMJRefresh_LastedUpdateTime";


@interface ESWeiXinSelectedViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *newsList;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ESWeChatLoadingView *loadingView;

@end

static NSInteger pageNum = 1;

@implementation ESWeiXinSelectedViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupRootView:self.view.frame];
    
    [self setupRefresh];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_tableView) {
        [self loadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Setup 初始化过程
//// 初始化数据
//- (void)initData
//{
//    newsList
//}

#pragma mark -- 加载数据
- (void)loadData
{
    ESWeChatDAO *dao = [ESWeChatDAO shareInstance];
    _newsList = nil;
    _newsList = [dao queryAllFromDB];
    
    if (![self canUpdateNewsList]) {
        if (_newsList != nil && _newsList.count > 0) {
            [self.tableView reloadData];
        } else {
            [self.loadingView setLoadingState:1];
            [self refreshData];
        }
    } else {
        [self refreshData];
    }
}

#pragma mark -- 网络相关
- (void)startNetTaskWithIsHeaderUpdate:(BOOL)headerUpdate
{

    headerUpdate?(pageNum = 1):(pageNum++);
    
    ESWeChatNetTask *netTask = [ESWeChatNetTask new];
    WS(weakSelf);
    [netTask setBlockWithReturnBlock:^(id returnValue) {
        if (headerUpdate) {
            weakSelf.newsList = nil;
            weakSelf.newsList = returnValue;
        } else {
            [weakSelf.newsList addObjectsFromArray:returnValue];
        }
        
        [weakSelf.tableView reloadData];
        
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        // 结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
        
        if (weakSelf.loadingView != nil && !weakSelf.loadingView.hidden) {
             weakSelf.loadingView.hidden = YES;
        }
  
    } WithErrorBlock:^(id errorCode) {
        
        ESNetResult *error = (ESNetResult *)errorCode;
        
        NSString *errorReason = [NSString stringWithFormat:@"%@",error.reason];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:errorReason message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    } WithFailureBlock:^{
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        // 结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
        
    }];

    [netTask startNetRequestTaskWithPageNum:[NSNumber numberWithInteger:pageNum] isHeaderUpdate:headerUpdate];
}

#pragma mark -- 布局相关
- (void)setupRootView:(CGRect)parentFrame
{
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:parentFrame];
    bgImageView.image = [UIImage imageNamed:@"WeChatTableViewBG"];
    [self.view insertSubview:bgImageView atIndex:0];
    
    self.navigationController.navigationBarHidden = YES;
    [self addCustomNavigationBarWithStyle:DefaultStyle customColor:[UIColor clearColor]];
    UIImageView *navigatonBarImage = [[UIImageView alloc]init];
    navigatonBarImage.frame = CGRectMake(0, 0, self.sgCustomNavigationBar.width, self.sgCustomNavigationBar.height);
    navigatonBarImage.image = [UIImage imageNamed:@"homeNavigationBarBG@2x"];
    [self.view insertSubview:navigatonBarImage atIndex:1];
    
    
    [self.sgCustomNavigationBar setTitle:@"微信精选"];
    self.sgCustomNavigationBar.titleLabel.textColor = [UIColor whiteColor];
    
//    //标题
//    UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
//    titleButton.backgroundColor = [UIColor clearColor];
//    titleButton.center = CGPointMake(self.navigationController.navigationBar.frame.size.width/2, self.navigationController.navigationBar.frame.size.height/2);
////    [titleButton setImage:[UIImage imageNamed:@"top_bar_logo_ic01"] forState:UIControlStateNormal];
////    [titleButton setImage:[UIImage imageNamed:@"top_bar_logo_ic02"] forState:UIControlStateHighlighted];
////    [titleButton addTarget:self action:@selector(refreshChannel) forControlEvents:UIControlEventTouchUpInside];
//    [self.sgCustomNavigationBar.navigationBar addSubview:titleButton];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.sgCustomNavigationBar.height, self.view.width, self.view.height-self.sgCustomNavigationBar.height-self.tabBarController.tabBar.height) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorInset = UIEdgeInsetsMake(0,13,0,13);
    [self.view addSubview:_tableView];
    
    
    
}

- (void)setupRefresh
{
    WS(weakSelf);
    //下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf startNetTaskWithIsHeaderUpdate:YES];
    }];
    [header setTitle:@"再拉一点 给你好看" forState:MJRefreshStateIdle];
    [header setTitle:@"松手 给你好看" forState:MJRefreshStatePulling];
    [header setTitle:@"稍等!只为给你更好的" forState:MJRefreshStateRefreshing];
    [header setTitle:@"别拉了 好看的都在这了" forState:MJRefreshStateNoMoreData];
    _tableView.mj_header = header;
    
    // 上拉刷新
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
         [weakSelf startNetTaskWithIsHeaderUpdate:NO];
    }];
    [footer setTitle:@"再拉一点 给你好看" forState:MJRefreshStateIdle];
    [footer setTitle:@"松手 给你好看" forState:MJRefreshStatePulling];
    [footer setTitle:@"稍等!只为给你更好的" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"别拉了 好看的都在这了" forState:MJRefreshStateNoMoreData];
    _tableView.mj_footer = footer;
}


-(ESWeChatLoadingView *)loadingView
{
    if(_loadingView == nil)
    {
        ESWeChatLoadingView *loadingView = [[ESWeChatLoadingView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.sgCustomNavigationBar.frame), self.view.frame.size.width, self.view.height - CGRectGetMaxY(self.sgCustomNavigationBar.frame))];
        [self.view addSubview:loadingView];
        loadingView.hidden = YES;
        _loadingView = loadingView;
        __weak typeof(self) weakSelf = self;
        _loadingView.buttonDidTap = ^()
        {
            [weakSelf refreshData];
        };
    }
    return _loadingView;
}

#pragma mark -- 事件相关
- (void)refreshData
{
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    [self.tableView.mj_header setLastUpdatedTimeKey:kESWeiXinSelectedVCLastedUpdateTimeKey];
}

#pragma mark -- 辅助函数
// 根据上次刷新时间判断现在是否自动刷新   大于2小时则自动刷新
- (BOOL)canUpdateNewsList
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader new];
    header.lastUpdatedTimeKey = kESWeiXinSelectedVCLastedUpdateTimeKey;
    NSDate *lastUpdateTime = header.lastUpdatedTime;
    
    if (lastUpdateTime == nil) {
        return NO;
    }
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    NSDateComponents *maxDateComponent = [[NSDateComponents alloc] init];
    [maxDateComponent setHour:2];
    NSDate *maxDepartDate = [calendar dateByAddingComponents:maxDateComponent toDate:lastUpdateTime options:0];
    
    NSDate *now = [NSDate date];
    if ([now compare:maxDepartDate] == NSOrderedAscending || [now compare:maxDepartDate] == NSOrderedSame) {
        return NO;
    }
    
    return YES;
}


#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_newsList != nil && _newsList.count > 0) {
        return _newsList.count;
    } else {
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ESWeChatTableViewcell *cell = [tableView dequeueReusableCellWithIdentifier:@"wechatNewsListCell"];
    if (cell == nil) {
        cell = [ESWeChatTableViewcell loadViewFromSameXibName];
        cell.backgroundColor = [UIColor clearColor];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    }
    
    WxNewsObject *item = [_newsList objectAtIndex:indexPath.row];
    cell.newsObject = item;
//    cell.titleLable.text = item.title;
//    cell.sourceLable.text = item.source;
//    NSLog(@"URL == %@",item.firstImg);
//    [cell.firstImg sd_setImageWithURL:[NSURL URLWithString:item.firstImg] placeholderImage:[UIImage imageNamed:@"NewsListdefult.png"]];
    return cell;
}


#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WxNewsObject *item = [_newsList objectAtIndex:indexPath.row];
    if (item == nil || item.url == nil || item.url.length <= 0) {
        return;
    }
    
    /// 添加阅读历史
    ESWeChatReadHistoryDAO *historyDAO =  [ESWeChatReadHistoryDAO shareInstance];
    [historyDAO insertReadHistoryData:item];
    
    self.hidesBottomBarWhenPushed = YES;
    ESWeiXinNewsDetailViewController *detailVC = [ESWeiXinNewsDetailViewController new];
    detailVC.isCanCollect = YES;
    detailVC.newsObject = item;
    detailVC.newsTitle = item.title;
    detailVC.newsURL = item.url;
    [self.navigationController pushViewController:detailVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
@end
